package com.group9.handinhand.social;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionKey;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;

import com.group9.handinhand.service.SocialUserService;

public class UsersConnectionRepositoryImpl implements UsersConnectionRepository {
	
	@Autowired
	SocialUserService socialUserService;
	
	private final ConnectionFactoryLocator connectionFactoryLocator;

	private final TextEncryptor textEncryptor;

	private ConnectionSignUp connectionSignUp;
	
	public UsersConnectionRepositoryImpl(ConnectionFactoryLocator connectionFactoryLocator, TextEncryptor textEncryptor) {
		this.connectionFactoryLocator = connectionFactoryLocator;
		this.textEncryptor = textEncryptor;
	}

	public ConnectionSignUp getConnectionSignUp() {
		return connectionSignUp;
	}
	
	public void setConnectionSignUp(ConnectionSignUp connectionSignUp) {
		this.connectionSignUp = connectionSignUp;
	}

	@Override
	public List<String> findUserIdsWithConnection(Connection<?> connection) {
		ConnectionKey key = connection.getKey();

		List<String> localUserIds = socialUserService.findUserIdsByProviderIdAndProviderUserId(key.getProviderId(), key.getProviderUserId());
		
		if (localUserIds.size() == 0 && connectionSignUp != null) {
			String newUserEmail = connectionSignUp.execute(connection);
			if (newUserEmail != null)
			{
				createConnectionRepository(newUserEmail).addConnection(connection);
				return Arrays.asList(newUserEmail);
			}
		}
		return localUserIds;
	}

	@Override
	public Set<String> findUserIdsConnectedTo(String providerId, Set<String> providerUserIds) {
		return null;
	}

	@Override
	public ConnectionRepository createConnectionRepository(String userId) {
		if (userId == null) {
			throw new IllegalArgumentException("userId cannot be null");
		}
		return new ConnectionRepositoryImpl(userId, connectionFactoryLocator, textEncryptor, socialUserService);
	}

}
